package org.jetlinks.pro.device.web.response;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Generated;
import lombok.Getter;
import lombok.Setter;
import org.jetlinks.pro.device.entity.DeviceProperty;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Flux;

import java.util.Comparator;
import java.util.List;
import java.util.function.Function;

@Getter
@Setter
@AllArgsConstructor(staticName = "of")
@Generated
public class DeviceTopPropertyView {
    @Schema(description = "时间")
    private String time;

    @Schema(description = "属性列表")
    private List<DeviceTopProperty> properties;

    public static Function<Flux<DeviceProperty>, Flux<DeviceTopPropertyView>> transfer(String pattern) {
        DateTimeFormatter formatter = DateTimeFormat.forPattern(pattern);

        return properties -> properties
            .groupBy(DeviceProperty::getFormatTime, Integer.MAX_VALUE)
            .flatMap(group -> {
                String time = group.key();
                return group
                    .filter(prop -> StringUtils.hasText(prop.getProperty()))
                    .groupBy(DeviceProperty::getProperty, Integer.MAX_VALUE)
                    .filter(propertyGroup -> propertyGroup.key() != null)
                    .flatMap(propertyGroup -> {
                        String property = propertyGroup.key();
                        return propertyGroup
                            .collectList()
                            .map(list -> DeviceTopProperty.of(property, list));
                    })
                    .collectList()
                    .map(list -> DeviceTopPropertyView.of(time, list));
            })
            //按时间排序
            .sort(Comparator
                      .<DeviceTopPropertyView, DateTime>comparing(pro -> DateTime.parse(pro.time, formatter))
                      .reversed());
    }
}
